﻿package org.xtown.bingluo.xtieba.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.SocketAddress;
import java.net.URL;
import java.util.HashMap;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.WifiLock;

public class NetUtils {
	private HttpURLConnection con = null;

	private static Context context;
	private static WifiLock mWifiLock;

	private int nettype = 0;
	private InputStream inputStream = null;

	public NetUtils(Context context) {
		this.context = context;
	}

	/**
	 * 检测网络状态
	 * 
	 * @return If the network normally returns true, otherwise false
	 */
	public static boolean isNetWorking(Context context) {
		boolean netSataus = false;
		ConnectivityManager conManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = conManager.getActiveNetworkInfo();
		if (networkInfo != null) { // 注意，这个判断一定要的哦，要不然会出错
			netSataus = networkInfo.isAvailable();

		}
		if (netSataus) {
			openWifi(context);
		}
		return netSataus;
	}

	// 判断是否网络连接
	public static boolean isConnectInternet(Context context) {
		boolean netSataus = false;
		ConnectivityManager conManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = conManager.getActiveNetworkInfo();
		if (networkInfo != null) { // 注意，这个判断一定要的哦，要不然会出错
			netSataus = networkInfo.isAvailable();

		}
		if (netSataus) {
			openWifi(context);
		}
		return netSataus;
	}
	
	/** 
     * 判断当前网络是否是wifi网络 
     * if(activeNetInfo.getType()==ConnectivityManager.TYPE_MOBILE) { //判断3G网 
     *  
     * @param context 
     * @return boolean 
     */  
    public static boolean isWifi(Context context) {  
        ConnectivityManager connectivityManager = (ConnectivityManager) context  
                .getSystemService(Context.CONNECTIVITY_SERVICE);  
        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();  
        if (activeNetInfo != null  
                && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {  
            return true;  
        }  
        return false;  
    }  
  
    /** 
     * 判断当前网络是否是3G网络 
     *  
     * @param context 
     * @return boolean 
     */  
    public static boolean is3G(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context  
                .getSystemService(Context.CONNECTIVITY_SERVICE);  
        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();  
        if (activeNetInfo != null  
                && activeNetInfo.getType() == ConnectivityManager.TYPE_MOBILE) {  
            return true;  
        }  
        return false;  
    }  

	/**
	 * 获取网络类型
	 * 
	 * @return 0代表是cmnet和wifi,1代表是cmwap
	 */
	public static int getNettype(Context context) {
		ConnectivityManager connectivityManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo(); // 获取网络连接是走Internet还是GPRS
		NetworkInfo mobNetInfo = connectivityManager
				.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); // 获取网络连接是走cmwap还是cmnet
		if (mobNetInfo != null && activeNetInfo != null
				&& activeNetInfo.getType() == 0
				&& mobNetInfo.getExtraInfo().equals("cmwap")) {
			return 1;
		} else {
			return 0;
		}
	}

	public static void openWifi(Context c) {
		WifiManager wm = (WifiManager) c.getSystemService(Context.WIFI_SERVICE);
		if (wm != null && wm.isWifiEnabled()) {
			System.out.println("WifiEnabled");
			mWifiLock = wm.createWifiLock("WifiService");//
			mWifiLock.setReferenceCounted(true);
			if (!mWifiLock.isHeld()) {
				mWifiLock.acquire();
			}
		}

	}

	/**
	 * 打开网络连接
	 * 
	 * @param path
	 *            网络地址
	 * @return
	 */
	public HttpURLConnection openConnection(String path) {

		if (path == null || "".equals(path.trim())
				|| !isConnectInternet(context)) {
			return null;
		}

		try {
			URL url = new URL(path);
			nettype = getNettype(context);
			if (nettype == 0) {
				openWifi(context);
				con = (HttpURLConnection) url.openConnection();
			} else if (nettype == 1) {
				SocketAddress proxyAddress = new InetSocketAddress(
						"10.0.0.172", 80);
				Proxy proxy = new Proxy(Proxy.Type.HTTP, proxyAddress);
				con = (HttpURLConnection) url.openConnection(proxy);
			}

			// System.out.println("url == > " + path);

			con.setConnectTimeout(25000);
			con.setReadTimeout(25000);
			// con.connect();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return con;
	}

	/**
	 * 获取网络资源
	 * 
	 * @return <b>length</b>: 资源长度 </br> <b>stream</b>: 资源InputStream
	 */
	public HashMap<String, Object> getInputStream() {
		HashMap<String, Object> mMap = new HashMap<String, Object>();
		int length = 0;
		try {
			if (con != null) {
				inputStream = con.getInputStream();
				length = con.getContentLength();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		mMap.put("length", length);
		mMap.put("stream", inputStream);

		return mMap;
	}

	/**
	 * 获取网络资源
	 * 
	 * @return <b>stream</b>: 资源InputStream
	 */
	public InputStream getInStream() {
		try {
			if (con != null) {
				inputStream = con.getInputStream();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return inputStream;
	}

	/**
	 * 关闭网络连接
	 */
	public void close() {
		try {
			if (inputStream != null)
				inputStream.close();
			if (con != null)
				con.disconnect();

			if (mWifiLock != null && mWifiLock.isHeld()) {
				mWifiLock.release();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 从输入流中获取String
	 * 
	 * @param stream
	 *            输入流
	 * @param bool
	 *            是否有必要关闭输入流
	 * @return 返回String
	 */
	public static String getInputStream2String(InputStream stream) {
		if (stream == null) {
			return null;
		}
		BufferedReader reader = new BufferedReader(
				new InputStreamReader(stream));
		StringBuilder sb = new StringBuilder();
		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sb.substring(0, sb.length() - 1).toString();
	}
}
